require 'Hpricot'

# a concrete Backup implementation for backing up tweets
class TwitterBackup < Backup
  # http://apiwiki.twitter.com/REST+API+Documentation
  
  attr_meta :username, :password
  
  validates_presence_of :username, :password
  
  def run
    tweet_xml = get "http://twitter.com/statuses/user_timeline/#{username}.xml?count=200"
    xml = tweet_xml + contacts_xml
    write output_path, xml
  end
  
  def output_path
    @output_path ||= "#{id}-twitter-#{username}"
  end

  private
    def contacts_xml
      friends = get_friends
      followers = get_followers
      
      unless friends.empty? && followers.empty?
        xml =   '<?xml version="1.0" encoding="utf-8"?>\n'
        xml +=  '<users>\n'
        xml +=  "<friends>\n#{get_friends}\n</friends>\n"
        xml +=  "<followers>\n#{get_followers}\n</followers>\n"    
        xml +=  '</users>\n'
      else
        xml = ''
      end
      
      xml
    end
      
    def get_friends
      base_url = "http://twitter.com/statuses/friends/#{username}.xml"
  
      friends = ''
      i = 1
      
      # build friends array
      while (1)
        data = Hpricot get(base_url + "?page=#{i}")

        friend_data = (data / "user")
        break if friend_data.empty?

        friends += friend_data.to_s
        i += 1
      end
      
      friends
    end

    def get_followers
      base_url = "http://twitter.com/statuses/followers/#{username}.xml"
      followers = ''
      i = 1

      # build followers array
      while (1)
        puts '.'
        url = base_url + "?page=#{i}"

        data = Hpricot get(url, :http_basic_authentication => [username, password])

        follower_data = (data / "user")
        break if follower_data.empty?

        followers += follower_data.to_s
        i += 1
      end

      followers
    end
    
end
